import java.io.*;
import javax.sound.sampled.*;


/**
 * @author  8100556811
 */
public class SimpleSoundPlayer {
	
	public static void main(String[] args)

	{
		//load
		
		SimpleSoundPlayer sound = new SimpleSoundPlayer("images/sound/voice.wav");
		
		//create the stream to play
		InputStream stream = new ByteArrayInputStream(sound.getSamples());
		
		//play
		sound.play(stream);
		
		//exit
		System.exit(0);
	}
	
	private AudioFormat format;
	/**
	 * @uml.property  name="samples"
	 */
	private byte[] samples;
	
	//opens a sound from a file
	public SimpleSoundPlayer(String filename)
	{
		try{
			AudioInputStream stream = AudioSystem.getAudioInputStream(new File(filename));
			format = stream.getFormat();
			
			//get the sample
			samples = getSamples(stream);
		}
		catch(UnsupportedAudioFileException ex)
		{
			ex.printStackTrace();
		}
		catch (IOException ex)
		{
			ex.printStackTrace();
		}
		
	}
	
	
	
	//get the samples
	
	/**
	 * @return
	 * @uml.property  name="samples"
	 */
	public byte[] getSamples()
	{
		return samples;			
	}
	
	//get the samples from an audioinputstream
	public byte[] getSamples(AudioInputStream audioStream)
	{
		int length = (int) (audioStream.getFrameLength()* format.getFrameSize());
		
		//read the stream
		byte[] samples = new byte[length];
		DataInputStream is = new DataInputStream(audioStream);
		try{
			is.readFully(samples);
		}
		catch (IOException ex)
		{
			ex.printStackTrace();
		}
		
		return samples;
	}
	
	// plays a stream
	
	public void play (InputStream source)
	{
		int bufferSize = format.getFrameSize() * Math.round(format.getSampleRate()/10);
		byte[] buffer = new byte[bufferSize];
		//create a line to play to
		
		SourceDataLine line = null;				
		try{
			DataLine.Info info = new DataLine.Info(SourceDataLine.class,format);
			line = (SourceDataLine) AudioSystem.getLine(info);
			line.open(format, bufferSize);
		}
		catch (LineUnavailableException ex)
		{
			ex.printStackTrace();
		}
		
		line.start();
		
		
		try{
			int numBytesRead = 0;
			while (numBytesRead!= -1)
			{
				numBytesRead = source.read(buffer,0,buffer.length);
				if (numBytesRead !=-1)
				{
					line.write(buffer, 0, numBytesRead);
				}
			}
		}
		catch (IOException ex)
		{
			ex.printStackTrace();
		}
		
		line.drain();
		line.close();
		
	}
	

}
